package com.library;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/get_book")
public class GetBookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setContentType("application/json; charset=UTF-8");

        String number = request.getParameter("number");
        PrintWriter out = response.getWriter();
        if (number == null || number.isEmpty()) {
            out.print("{\"success\": false, \"message\": \"Missing 'number' parameter\"}");
            return;
        }

        Book book = BookDAO.findBookByNumber(number);
        if (book != null) {
            out.print("{");
            out.print("\"success\": true, ");
            out.print("\"number\": \"" + book.getNumber() + "\", ");
            out.print("\"name\": \"" + book.getName() + "\", ");
            out.print("\"author\": \"" + book.getAuthor() + "\"");
            out.print("}");
        } else {
            out.print("{\"success\": false, \"message\": \"Book not found\"}");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
}

